package domain;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;

/**
 * Send a request to JCDecaux
 * 
 * @author Smouha
 * 
 */
public class JCDecauxQuery {

	public Map<Integer, JCDecauxObject> sendRequest() throws IOException {
		String sURL = "https://api.jcdecaux.com/vls/v1/stations?contract=paris&apiKey=07c7589f7f1255ffddbc55ec716d368ef5774a84";
		URL url = new URL(sURL);

		InputStream is = url.openStream();

		JsonReader rdr = Json.createReader(is);
		JsonArray array = rdr.readArray();

		is.close();

		Map<Integer, JCDecauxObject> mapRes = new HashMap<Integer, JCDecauxObject>();

		for (JsonValue value : array) {
			ValueType vt = value.getValueType();
			if (vt == ValueType.OBJECT) {
				JCDecauxObject jcDecauxObj = new JCDecauxObject();

				JsonObject jsonObj = (JsonObject) value;
				jcDecauxObj.setNumber(jsonObj.getInt("number"));
				jcDecauxObj.setName(jsonObj.getString("name"));
				jcDecauxObj.setAddress(jsonObj.getString("address"));

				jcDecauxObj.setLatitude(jsonObj.getJsonObject("position")
						.getJsonNumber("lat").doubleValue());
				jcDecauxObj.setLongitude(jsonObj.getJsonObject("position")
						.getJsonNumber("lng").doubleValue());

				String sStatus = jsonObj.getString("status");
				jcDecauxObj.setStatus(EStatus.strToValue(sStatus));
				jcDecauxObj.setBikeStands(jsonObj.getInt("bike_stands"));
				jcDecauxObj.setAvailableBikeStands(jsonObj
						.getInt("available_bike_stands"));
				jcDecauxObj
						.setAvailableBikes(jsonObj.getInt("available_bikes"));

				mapRes.put(jcDecauxObj.getNumber(), jcDecauxObj);

			}
		}
		return mapRes;
	}
}
